package com.link.base.base.mpconfig.controller;

import com.alibaba.fastjson.JSONObject;
import com.link.base.base.mpconfig.model.*;
import com.link.base.sms.model.Template;
import com.link.base.base.mpconfig.service.MpService;
import com.link.base.base.mpconfig.service.MpTemplateService;
import com.link.base.base.mpconfig.service.MpTokenService;
import com.link.core.cllog.LCLogger;
import com.link.base.wechat.basic.util.WeixinHttpUtil;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.util.JsonUtil;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 小程序模板消息接口类
 *
 * @author: 闫有霞
 * @date: 2018-12-06
 * @comments:
 */
@Controller
@RequestMapping("/link/mpTemplate")
public class MpTemplateController extends BasicController<Template> {

    @Resource
    private Environment env;

    @Resource
    private KeyGenerateService keyGenerateService;

    @Resource
    private MpTemplateService mpTemplateService;

    @Resource
    private MpService mpService;

    @Resource
    private MpTokenService mpTokenService;

    @Override
    public BasicService<Template> getBasicService() throws Exception {
        return mpTemplateService;
    }

    /**
     * @createdBy 闫有霞
     * @date 2018/12/3
     * @methods: getMpTemplate
     * @param: mp
     * @return:
     * @description: 获取帐号下已存在的模板列表
     **/
    @RequestMapping(value = "getMpTemplate", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> getMpTemplate(@RequestBody Mp entity) {
        Map<String, Object> map = new HashMap<>(16);
        try {
            Mp mp = new Mp();
            mp = mpService.queryById(entity);
            mp.setRows(entity.getRows());
            /*通过lnk_mp_config 中的appId 及 appSecret 获取 小程序的 token */
            String accesstoken = mpTokenService.getMpAccessToken(mp);
            JSONObject paramJson = new JSONObject();
            // 将参数写入到paramJson对象中
            paramJson.put("offset",0);
            /*用于分页，表示从offset开始。从 0 开始计数*/
            paramJson.put("count", mp.getRows());
            /*用于分页，表示拉取count条记录。最大为 20。最后一页的list长度可能小于请求的count*/
            String data = JsonUtil.toString(paramJson);
            String requestUrl = env.getProperty("weixinuri.mpTempLateUrl").replace("ACCESS_TOKEN", accesstoken);
            JSONObject json = WeixinHttpUtil.httpRequest(requestUrl, "POST", data);
            Map<String, Object> exampleMap = new HashMap<>(16);
            String templateList = "list";
            if (json.containsKey(templateList)) {
                for (int i = 0; i < json.getJSONArray(templateList).size(); i++) {
                    String example = JSONObject.parseObject(json.getJSONArray("list").get(i).toString()).get("example").toString();
                    if (example != null && example.contains("\n")) {
                        if (example.contains("\r\n")) {
                            example = example.replace("\r\n", "<br/>");
                        } else {
                            example = example.replace("\n", "<br/>");
                        }
                    }
                    exampleMap.put(JSONObject.parseObject(
                            json.getJSONArray("list").get(i).toString()).get("template_id").toString(), example);
                }
            }
            map.put("result", json);
            map.put("example", exampleMap);
            map.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            map.put("success", false);
            map.put("result", e.getMessage());
        }
        return map;
    }

    /**
     * 获取小程序账号的类目
     *
     * @author lujiang
     * @date 2019-11-26
     * @param entity 小程序对象
     * @return
     */
    @RequestMapping(value = "/getMpCategory", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> getMpCategory(@RequestBody Mp entity) {
        Map<String, Object> result = new HashMap<>(8);
        try {
            List<Mp> mps = mpTemplateService.getMpCategory("替换为真正的token");
            result.put("result", mps);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 获取帐号所属类目下的公共模板标题
     *
     * @author lujiang
     * @date 2019-11-26
     * @param entity
     * @return
     */
    @RequestMapping(value = "/getPubTemplateTitleList", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> getPubTemplateTitleList(@RequestBody Mp entity) {
        Map<String, Object> result = new HashMap<>(8);
        try {
            List<PubTemplateTitle> pubTemplateTitles = mpTemplateService.getPubTemplateTitleList("替换为真正的token");
            result.put("result", pubTemplateTitles);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 获取模板标题下的关键词列表
     *
     * @author lujiang
     * @date 2019-11-26
     * @param entity
     * @return
     */
    @RequestMapping(value = "/getPubTemplateKeyWordsById", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> getPubTemplateKeyWordsById(@RequestBody PubTemplateTitle entity) {
        Map<String, Object> result = new HashMap<>(8);
        try {
            List<PubTemplateKeyWord> pubTemplateKeyWords = mpTemplateService.getPubTemplateKeyWordsById(entity,"");
            result.put("result", pubTemplateKeyWords);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 获取当前帐号下的个人模板列表
     *
     * @author lujiang
     * @date 2019-11-26
     * @param entity
     * @return
     */
    @RequestMapping(value = "/getTemplateList", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> getTemplateList(@RequestBody Mp entity) {
        Map<String, Object> result = new HashMap<>(8);
        try {
            JSONObject json = mpTemplateService.getTemplateList(entity);
            result.put("result", json);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 发送订阅消息
     *
     * @author lujiang
     * @date 2019-11-26
     * @param entity
     * @return
     */
    @RequestMapping(value = "/subscribeMessageSend", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> subscribeMessageSend(@RequestBody SendTempMessage entity) {
        Map<String, Object> result = new HashMap<>(8);
        try {
            result = mpTemplateService.subscribeMessageSend(entity);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 发送小程序订阅消息
     * @author 姚江漪
     * @date 2019/11/15 16:14
     */
    @RequestMapping(value = "sendMpSubscribeMsg", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> sendMpSubscribeMsg(@RequestBody SendTempMessage entity) {
        Map<String, Object> map = new HashMap<>(16);
        try {
            mpTemplateService.sendMpSubscribeMsg(entity);
            map.put("success", true);
            map.put("result", "");
        } catch (Exception e) {
            LCLogger.withException(e);
            map.put("success", false);
            map.put("result", e.getMessage());
        }
        return map;
    }
}
